package com.example.lanchat;

import android.os.Message;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TcpServer {
    public static final int MSG_TCPCONN=3;
    Boolean isRunning;
    public static final int MSG_RECEIVE = 1;
    public static final int MSG_SEND = 2;
    public static final int MSG_TCPISCONN = 4;
    android.os.Handler myHandler;
    Boolean isOpen = false;
    String msg;
    public TcpServer(android.os.Handler myHandler) {
        this.myHandler = myHandler;
    }
    public void startServer(){
      Thread  t=new Thread(new MyRunnable());
        t.start();
        isRunning=true;
    }
    public void sendMSG(String msg){
        this.msg=msg;
        isOpen=true;
    }
    class MyRunnable implements  Runnable{

        @Override
        public void run() {
            //创建一个Server Socket对象
            ServerSocket ss=null;
            try {
                //监听端口
                ss=new ServerSocket(6666);
                System.out.println("server is running...");
                for (;;){
                    //监听是否有链接请求，如果有，创建Socket
                    Socket socket=ss.accept();
                    Message m =new Message();
                    m.what=TcpServer.MSG_TCPCONN;
                    myHandler.sendMessage(m);
                    System.out.println("connected from"+socket.getRemoteSocketAddress());
                    Thread t=new ReadThread(socket);
                    t.start();
                    Thread w= new WriteThread(socket);
                    w.start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    class ReadThread extends Thread {
        Socket socket;
        public ReadThread(Socket socket){
            this.socket=socket;
        }
        @Override
        public void run() {
            try {
                InputStream input = socket.getInputStream();
                OutputStream output = socket.getOutputStream();
                processMessage(input, output);
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    socket.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }

        private void processMessage(InputStream input, OutputStream output) throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
            while (isRunning) {
                //读取对方发送的消息，并更新
                String ss = reader.readLine();
                if (ss == null) {

                } else {
                    Message message = new Message();
                    message.what = MSG_RECEIVE;
                    message.obj = ss;
                    myHandler.sendMessage(message);
                }
            }
        }
    }
    class WriteThread extends Thread {
        Socket socket;
        public WriteThread(Socket socket){
            this.socket=socket;
        }
        @Override
        public void run() {
            try {
                InputStream input = socket.getInputStream();
                OutputStream output = socket.getOutputStream();
                processMessage(input, output);
                MainActivity.isBluetooth=false;
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    socket.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                System.out.println("client disconnected");
            }
        }

        private void processMessage(InputStream input, OutputStream output) throws IOException {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
            //发送消息调用，按下按钮发送
            while (isRunning) {
                if (isOpen) {
                    writer.write(msg + "\n");
                    writer.flush();
                    isOpen = false;
                }
            }
        }
    }
}
